<template>
  <div class="pd30 flex user flexjcsb">
    <div class="panelWrap user-main">
      <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
        <div>用户管理平台</div>
      </div>
      <div class="con">
        <div class="con-row flex flexac pl search-box">
          <div class="inputLable2 flex flexac">
            <!-- <span>用户名：</span> -->
            <el-input v-model="param.name" class="user-input" style="height: 38px;margin-top: 4px" placeholder="请输入用户名称..." @input="getUserList" />
          </div>
          <div class="groupbtn flex m-l-40 ">
            <el-button class="flex flexac m-r-20 fs14" size="small" type="warning" @click="getUserList"><i class="co-i" /><span class="search1">查 询</span></el-button>
            <el-button class="flexcenter co-empty m-l-25" type="info" @click="handleEmptySearch"><i class="iconfont icon-qingkong" />清 空</el-button>
          </div>
        </div>
        <div class="con-row flex flexac flexjcsb pl">
          <el-button class="defaultbtn" type="primary" @click="handleRefresh"><i class="el-icon-refresh" :class="refresh?'goRefresh':''" />刷 新</el-button>
          <div class="m-r-25 flex">
            <el-button class="defaultbtn" type="primary" @click="handleAdd"><i class="el-icon-circle-plus-outline" />添加新用户</el-button>
            <el-button class="defaultbtn" type="primary" @click="handleExportExcel"><i class="iconfont icon-wenjiandaochu" />导出</el-button>
            <div class="pre m-l-10">
              <el-button class="defaultbtn pre" type="primary" @click="handleSenior('field')"><i class="iconfont icon-shezhi" />字段
              </el-button>
              <div class="selectUl" :class="seniorSet.field?'showSelectUl':'hideSelectUl'">

                <div v-for="(item,i) in tablehead" :key="i" class="li">
                  <el-checkbox v-model="item.isShow">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <div class="pre m-l-10">
              <el-button class="defaultbtn" type="primary" @click="handleSenior('sortable')"><i class="iconfont icon-shezhi" />排序</el-button>
              <div class="selectUl" :class="seniorSet.sortable ? 'showSelectUl' : 'hideSelectUl'">

                <div v-for="(item,i) in tablehead" v-if="item.isShow" :key="i" class="li">
                  <el-checkbox v-model="item.sortable">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <!-- <el-button class="defaultbtn" @click="handleExportExcel" type="primary"><i class="iconfont icon-shezhi"></i>固定</el-button> -->
          </div>
        </div>

        <el-table
          id="userList"
          ref="userList"
          class="con-table"
          type="expand"
          :data="userList"
          highlight-current-row
        >

          <!-- <el-table-column label="个人头像" align="center">
            <template slot-scope="scope">
              <el-image :src="scope.row.avatarUrl" class="avatar" lazy>
                <div slot="error" class="image-slot">
                  <el-image class="errorImg avatar" :src="url" lazy fit="fill" />
                </div>
              </el-image>
            </template>
          </el-table-column> -->

          <template v-for="(item, i) in tablehead">
            <el-table-column v-if="item.isShow" :key="i" :width="item.width" align="center" :sortable="item.sortable" :show-overflow-tooltip="true" :prop="item.prop" :label="item.label" />
          </template>

          <!-- <el-table-column label="角色名称" align="center">
            <template slot-scope="scope">
              <ul>
                <li v-for="(item, i) in scope.row.roles" :key="i" :color="tagColor" class="tag">{{ item.roleName }}</li>
              </ul>
            </template>
          </el-table-column>

          <el-table-column label="机构ID" align="center" width="72">
            <template slot-scope="scope">
              <ul>
                <li v-for="(item, i) in scope.row.orgs" :key="i" :color="tagColor" class="tag">{{ item.orgId }}</li>
              </ul>
            </template>
          </el-table-column>

          <el-table-column label="机构名称" align="center">
            <template slot-scope="scope">
              <ul v-if="scope.row.orgs.length > 0">
                <li v-for="(item, i) in scope.row.orgs" :key="i" :color="tagColor" class="tag">
                  {{ scope.row.roles[0].roleName === '维保预备案角色' ? '--' : scope.row.roles[0].roleName === '物业预备案角色' ? '--' : item.orgName }}
                </li>
              </ul>
            </template>
          </el-table-column> -->

          <el-table-column label="是否绑定微信" align="center">
            <template slot-scope="scope">
              <div title="平台需绑定微信" :class="`wechat${scope.row.wxId === '' ? false : true} iconfont ${scope.row.wxId === '' ? '' : 'icon-weixin'}` " />
            </template>
          </el-table-column>

          <el-table-column label="用户状态" width="80" align="center">
            <template slot-scope="scope">
              <span :class="`status status${scope.row.status} flex`">{{ scope.row.status === 1 ? '待审核' : scope.row.status === 2 ? '已启用' : '已停用' }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="name" align="center" width="340" label="基本操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status === 1" class="defaultbtn" type="success" @click="handleEnable(scope.$index, scope.row)">
                <i class="el-icon-edit-outline" />启 用
              </el-button>
              <el-button v-if="scope.row.status === 2" class="defaultbtn" type="info" @click="handleStop(scope.$index, scope.row)">
                <i class="el-icon-edit-outline" />停 用
              </el-button>
              <el-button v-if="scope.row.status === 3" class="defaultbtn" type="success" @click="handleRestart(scope.$index, scope.row)">
                <i class="el-icon-edit-outline" />启 用
              </el-button>
              <el-button
                class="defaultbtn"
                type="primary"
                @click="handleEdit(scope.$index, scope.row)"
              >
                <i class="el-icon-tickets" />
                编 辑
              </el-button>
              <!-- <el-button class="defaultbtn" type="success" @click="handleExamine">
                <i class="el-icon-edit-outline" />审 核
              </el-button> -->
              <el-button class="defaultbtn" type="danger" plain @click="handleDeleteBtn(scope.$index, scope.row)">
                <i class="el-icon-delete" />删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="paginationWrap flex"
          :current-page="paging.pageIndex"
          :page-sizes="paging.pageSizeArr"
          :page-size="paging.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 启用用户同步框 -->
    <Enable v-model="enableVisible" :data="enableData" @update="handleEnUpdate" @handleRefresh="handleRefresh" />
    <!-- 添加/编辑用户 -->
    <UserDialog v-model="userVisible" :data="editUser" :is-edit="isEdit" @handleRefresh="handleRefresh" @handleCloseDialog="handleUserCloseDialog" />
  </div>
</template>

<script>

import UserDialog from './dialog'
import Enable from './dialog/enable'
import { findUserList, deleteUser, findUserDetail, userDisable, userEnable } from '@/api/baseInfo/authority/user'
// import { findRoleList } from '@/api/baseInfo/authority/role'
import { showNotice, formatDateTime } from '@/utils/toolclass'
import storage from '@/utils/storage'

export default {
  components: { UserDialog, Enable },
  data() {
    return {
      value1: '',
      tagColor: '#ffffff',
      userStatus: null,
      userType: 1,
      username: '',
      enableTitle: '启 用',
      coData: {
        coType: null
      },
      isEdit: false,
      userVisible: false,
      enableData: {},
      enableVisible: false,
      userList: [],
      roleList: [],
      editUser: {},
      refresh: false,
      url: require('@/assets/error.png'),
      paging: {
        pageIndex: 1,
        pageSize: 10,
        pageSizeArr: [10, 15, 20, 35],
        total: 0
      },
      param: {
        id: '',
        name: ''
      },
      tablehead: [
        {
          index: 0,
          prop: 'index',
          label: '序号',
          width: '80',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 1,
          prop: 'name',
          label: '用户名称',
          width: '140',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 2,
          prop: 'account',
          label: '登录账号',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 3,
          prop: 'mobile',
          label: '手机号码',
          width: '120',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 4,
          prop: 'email',
          label: '电子邮箱',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 5,
          prop: 'expiredDate',
          label: '到期日期',
          sortable: false,
          fixed: true,
          isShow: true
        }
        // {
        //   index: 6,
        //   prop: 'identificationNumber',
        //   label: '手机识别号',
        //   sortable: false,
        //   fixed: true,
        //   isShow: true
        // }
        // {
        //   index: 7,
        //   prop: 'pushId',
        //   label: '手机推送ID',
        //   sortable: false,
        //   fixed: true,
        //   isShow: true
        // }
        // {
        //   index: 8,
        //   prop: 'pwd',
        //   label: '密码',
        //   sortable: false,
        //   fixed: true,
        //   isShow: true
        // },
        // {
        //   index: 9,
        //   prop: 'wxId',
        //   label: '微信ID',
        //   sortable: false,
        //   fixed: true,
        //   isShow: true
        // }
      ],
      seniorSet: {
        'field': false,
        'sortable': false
      }
    }
  },
  // computed: {
  //   ResAll() {
  //     return this.$store.state.user.res
  //   }
  // },
  created() {
    this.userInfo = JSON.parse(storage.get('data'))
    // this.getRoleList()
    this.getUserList()
  },
  mounted() {
    this.$storage.set('upUrl', JSON.stringify({ 'path': '/authority/user' }))
  },
  methods: {
    // 获取角色列表
    // getRoleList() {
    //   findRoleList('', '', 1, 100).then(res => {
    //     if (res.code === '000000') {
    //       // console.log(res)
    //       this.roleList = res.data
    //     }
    //   })
    // },
    // 获取用户列表
    getUserList() {
      findUserList(this.param.id, this.param.name, this.paging.pageIndex, this.paging.pageSize).then(res => {
        if (res.code === '000000') {
          // console.log('rese', res)
          this.userList = res.data.map((item, i) => {
            const items = {
              index: i + 1,
              account: item.account,
              avatarUrl: item.avatarUrl,
              email: item.email,
              expiredDate: item.expiredDate,
              id: item.id,
              identificationNumber: item.identificationNumber,
              mobile: item.mobile,
              name: item.name,
              phoneModel: item.phoneModel,
              pushId: item.pushId,
              pwd: item.pwd,
              roleIds: item.roleIds,
              status: item.status,
              wxId: item.wxId
            }
            return items
          })
          this.paging = {
            pageIndex: res.pager.pageIndex,
            pageSize: res.pager.pageSize,
            total: res.pager.totalSize
          }
        }
      })
    },
    // 启用用户弹出框
    handleEnable(index, row) {
      this.enableVisible = true
      this.enableData = row
    },
    handleEnUpdate(row) {
      if (row.code === '000000') {
        this.enableTitle = '禁 用'
        this.enableVisible = false
      }
    },
    // 禁用用户
    handleStop(index, row) {
      // console.log(row)
      this.$alert('确定禁用此用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.handleStatus(row.id)
          }
        }
      })
    },
    // 禁用用户
    handleStatus(id) {
      // console.log(id)
      userDisable(id).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '禁用成功')
          this.getUserList()
        } else {
          if (res.msg === '失败') {
            showNotice('error', '提示', '禁用失败')
          } else {
            showNotice('error', '提示', res.msg)
          }
        }
      })
    },
    // 禁用用户后重新启用用户
    handleRestart(index, row) {
      this.$alert('确定重新启用此用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.handleSubmit(row.id)
          }
        }
      })
    },
    handleSubmit(id) {
      userEnable(id).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '启用成功')
          this.getUserList()
        } else {
          if (res.msg === '失败') {
            showNotice('error', '提示', '启用失败')
          } else {
            showNotice('error', '提示', res.msg)
          }
        }
      })
    },
    // 删除用户
    handleDeleteBtn(index, row) {
      this.$alert('这个操作会删除和它相关联的所有数据,确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.handleDelete(row.id)
          }
        }
      })
    },
    handleDelete(id) {
      deleteUser(id).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '删除成功')
          this.getUserList()
        }
      })
    },
    // 用户详情
    handleDetail(userId) {
      // findUserDetail(userId).then(res => {
      //   // console.log(res)
      // })
    },
    // 编辑用户
    handleEdit(index, row) {
      this.userVisible = true
      this.isEdit = true
      // console.log(row)
      findUserDetail(row.id).then(res => {
        if (res.code === '000000') {
          // console.log(res)
          this.editUser = {
            account: res.data.account,
            avatarUrl: res.data.avatarUrl,
            email: res.data.email,
            expiredDate: res.data.expiredDate,
            id: res.data.id,
            identificationNumber: res.data.identificationNumber,
            mobile: res.data.mobile,
            name: res.data.name,
            phoneModel: res.data.phoneModel,
            pushId: res.data.pushId,
            pwd: res.data.pwd,
            password: '',
            roleIds: res.data.roleIds,
            status: res.data.status,
            wxId: res.data.wxId
          }
        }
      })
    },
    // 添加用户
    handleAdd() {
      this.userVisible = true
      this.isEdit = false
      this.editUser = {
        account: '',
        avatarUrl: '',
        email: '',
        id: 0,
        mobile: '',
        name: '',
        pwd: '',
        roleIds: []
      }
    },
    handleExportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        const tHeader = ['用户ID', '用户名称', '登陆账号', '手机号码', '电子邮箱', '到期日期', '用户状态']
        const filterVal = ['userId', 'name', 'account', 'mobile', 'email', 'expiredDate', 'status']
        const data = this.formatJson(filterVal, this.userList)
        export_json_to_excel(tHeader, data, '用户列表(' + formatDateTime().ymd) + ')'
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleSenior(type) {
      if (type === 'field') {
        this.seniorSet.field = !this.seniorSet.field
      }
      if (type === 'sortable') {
        this.seniorSet.sortable = !this.seniorSet.sortable
      }
    },
    handleRefresh() {
      this.refresh = true
      this.getUserList()
      setTimeout(() => {
        this.refresh = false
      }, 1200)
    },
    handleUserCloseDialog() {
      this.userVisible = !this.userVisible
    },
    handleSizeChange(val) {
      this.paging.pageSize = val
    },
    handleCurrentChange(val) {
      this.paging.currentPage = val
    },
    getMenuDetail(resourceId, systemId) {
      this.dataList = []
      // fetchDetail(resourceId, systemId).then((res) => {
      //   console.log(res)
      //   this.dataList.push(res.data)
      // })
    },
    // 清空
    handleEmptySearch() {
      this.param.name = ''
      this.getUserList()
    }
  }
}
</script>

<style lang="scss">
.user {
  .user-main {
    .el-icon-tickets:before,
    .el-icon-edit-outline:before,
    .el-icon-remove-outline:before,
    .el-icon-circle-check:before {
      margin-right: 4px;
    }
    .image-slot {
      width: 60px;
    }
    .user-input {
      width: 240px;
    }
    .tag {
      border: 0;
      color: #606266;
      font-size: 14px;
    }
    .avatar {
      width: 60px;
    }
    .status {
      border-radius: 5px;
      padding: 3px;
      justify-content: center;
      width: 60px;
    }
    .status1 {
      color: #E6A23C;
      border: 1px solid #E6A23C;
    }
    .status2 {
      color: #67C23A;
      border: 1px solid #67C23A;
    }
    .status3 {
      color: #909399;
      border: 1px solid #909399;
    }
  }
  .wechattrue {
    color: #3cb371;
    font-size: 32px;
    line-height: 32px;
  }
}
</style>
